package cn.fintecher.pangolin.service.business.web;

import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.CaseWarningInfo;
import cn.fintecher.pangolin.entity.mysql.CaseInfo;
import cn.fintecher.pangolin.service.business.model.request.CaseWarningInfoRequest;
import cn.fintecher.pangolin.service.business.repository.elasticsearch.CaseWarningInfoRepository;
import cn.fintecher.pangolin.service.business.repository.jparepository.CaseInfoRepository;
import cn.fintecher.pangolin.service.business.service.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.IteratorUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @Author:胡艳敏
 * @Desc: 警告信息查询
 * @Date:Create 2018/9/14
 */
@RestController
@RequestMapping("/api/caseWaringInfoController")
@Api(value = "警告信息查询", description = "警告信息查询")
public class CaseWaringInfoController {

    Logger logger = LoggerFactory.getLogger(CaseWaringInfoController.class);
    @Autowired
    private CaseWarningInfoRepository caseWarningInfoRepository;

    @Autowired
    private BaseService baseService;

    @Autowired
    private CaseInfoRepository caseInfoRepository;

    @GetMapping("/queryCaseWarningInfo")
    @ApiOperation(value = "查询警告信息", notes = "查询警告信息")
    public ResponseEntity<List<String>> queryPublicCase(@RequestParam String caseId) {
        logger.debug("查询警告信息 查询条件{}", caseId);

        List<String> responseWaring = new ArrayList<>();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        Optional<CaseInfo> byId = caseInfoRepository.findById(caseId);
        if (byId.isPresent()) {
            builder.must(matchPhraseQuery("batchNumber", byId.get().getBatchNumber()))
                    .must(matchPhraseQuery("certificateNo", byId.get().getCertificateNo()));
            Iterable<CaseWarningInfo> search = caseWarningInfoRepository.search(builder);
            if (search.iterator().hasNext()) {
                IteratorUtils.toList(search.iterator()).forEach(caseWarningInfo -> responseWaring.add(caseWarningInfo.getMsg()));
            }
        }
        return new ResponseEntity<>(responseWaring, HttpStatus.OK);
    }

    @PostMapping("/insertCaseWarningInfo")
    @ApiOperation(value = "添加警告信息", notes = "添加警告信息")
    public ResponseEntity insertCaseWarningInfo(@RequestBody CaseWarningInfoRequest request,
                                                @RequestHeader(value = "X-UserToken") String token) {
        logger.debug("添加警告信息", request);
        CaseWarningInfo caseWarningInfo = new CaseWarningInfo();
        BeanUtils.copyProperties(request, caseWarningInfo);
        UserModel userModel = baseService.getUserByToken(token);
        Optional<CaseInfo> byId = caseInfoRepository.findById(request.getCaseId());
        if (byId.isPresent()) {
            CaseInfo baseCase = byId.get();
            caseWarningInfo.setCaseId(baseCase.getId());
            caseWarningInfo.setCertificateNo(baseCase.getCertificateNo());
            caseWarningInfo.setPrincipalId(baseCase.getPrincipalId());
            caseWarningInfo.setOperator(userModel.getUsername());
            caseWarningInfo.setOperatorTime(ZWDateUtil.getNowDateTime());
            caseWarningInfo.setBatchNumber(baseCase.getBatchNumber());
            caseWarningInfo.setCardNo(Objects.nonNull(baseCase.getCardNo()) ? baseCase.getCardNo() : null);
            caseWarningInfoRepository.save(caseWarningInfo);
        }
        return new ResponseEntity<>(null, HttpStatus.OK);
    }

    @PostMapping("/editCaseWarningInfo")
    @ApiOperation(value = "修改警告信息", notes = "修改警告信息")
    public ResponseEntity editCaseWarningInfo(@RequestBody CaseWarningInfoRequest request,
                                              @RequestHeader(value = "X-UserToken") String token) {
        logger.debug("修改警告信息", request);
        CaseWarningInfo caseWarningInfo = caseWarningInfoRepository.findById(request.getWarnInfoId()).get();
        UserModel userModel = baseService.getUserByToken(token);
        caseWarningInfo.setOperator(userModel.getUsername());
        caseWarningInfo.setOperatorTime(ZWDateUtil.getNowDateTime());
        caseWarningInfo.setMsg(request.getMsg());
        caseWarningInfoRepository.save(caseWarningInfo);
        return new ResponseEntity<>(null, HttpStatus.OK);
    }

    @DeleteMapping("/deleteCaseWarningInfo")
    @ApiOperation(value = "删除警告信息", notes = "删除警告信息")
    public ResponseEntity insertCaseWarningInfo(@RequestParam String infoId,
                                                @RequestHeader(value = "X-UserToken") String token) {
        logger.debug("删除警告信息", infoId);
        CaseWarningInfo caseWarningInfo = new CaseWarningInfo();
        caseWarningInfo.setId(infoId);
        caseWarningInfoRepository.delete(caseWarningInfo);
        return new ResponseEntity<>(null, HttpStatus.OK);
    }

    @GetMapping("/queryCaseWarningInfoList")
    @ApiOperation(value = "查询警告信息列表", notes = "查询警告信息列表")
    public ResponseEntity<Page<CaseWarningInfo>> queryPublicCase(@RequestParam String caseId, Pageable pageable) {
        logger.debug("查询警告信息 查询条件{}", caseId);

        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        qb.must(termsQuery("caseId.keyword", caseId));
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withPageable(pageable)
                .withQuery(qb).build();
        Page<CaseWarningInfo> page = caseWarningInfoRepository.search(searchQuery);
        return ResponseEntity.ok().body(page);
    }
}
